//
//  CountDownTool.m
//  CYWFrame
//
//  Created by Macx on 2017/7/26.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "CountDownTool.h"

@implementation CountDownTool

+ (void)timeCountDown:(UIButton *)sender second:(int)second {
    
    //注意＊＊这里不需要✳️号 可以理解为dispatch_time_t 已经包含了
    dispatch_source_t time;
    
    // 关闭按钮的响应事件能力
    [sender setUserInteractionEnabled:NO];
    
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    //创建一个定时器
    time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)(1.0* NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(time, start, interval, 0);
    //设置回调
    __block int count = ++second;
    dispatch_source_set_event_handler(time, ^{
        
        //设置当执行60次是取消定时器
        count--;
        if(count == 0){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                // 打开按钮的响应事件能力
                [sender setUserInteractionEnabled:YES];
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
            
            // 移除定时器
            dispatch_cancel(time);
            [sender setUserInteractionEnabled:YES];
            
        }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:[NSString stringWithFormat:@"%d S", count] forState:UIControlStateNormal];
            });
            
        }
    });
    //由于定时器默认是暂停的所以我们启动一下
    //启动定时器
    dispatch_resume(time);
    
}

@end
